package com.gec.anan.driver.service.impl;

import com.gec.anan.driver.config.MinioProperties;
import com.gec.anan.driver.service.FileService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class FileServiceImpl implements FileService {
    @Autowired
    private MinioProperties minioProperties;

    //minio文件上传
    @Override
    public String upload(MultipartFile multipartFile) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        //1.创建客户端对象
        MinioClient minioClient = MinioClient.builder()
                .endpoint(minioProperties.getEndpointUrl())
                .credentials(minioProperties.getAccessKey(), minioProperties.getSecreKey())
                .build();
        //2.判断桶是否存在
        boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
        // 3.不存在则创建一桶
        if(!found){
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
        }else {
            //存在
            System.out.println("Bucket 'gec-bucket' already exists.");
        }
        //4.设置存储对象名称
        String extFileName = multipartFile.getOriginalFilename()
                .substring(multipartFile.getOriginalFilename().lastIndexOf("."));
        String fileName = new SimpleDateFormat("yyyyMMdd")
                .format(new Date())+"/"+ UUID.randomUUID().toString().replaceAll("-", "")+"."+extFileName;
        //文件上传
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(minioProperties.getBucketName())
                .stream(multipartFile.getInputStream(), multipartFile.getSize(), -1)
                .object(fileName)
                .build();
        minioClient.putObject(putObjectArgs);

        return minioProperties.getEndpointUrl() + "/" + minioProperties.getBucketName() + "/" + fileName ;
    }
}
